package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FocusApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @DubboReference
    private FocusApi focusApi;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 上传视频
     * @param videoThumbnail 封面图片文件
     * @param videoFile  视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if(videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if(StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0301","video",videoId);
    }

    //查询视频列表
    @Cacheable(
            value="videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")  //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND +UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if(!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if( (page -1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e->Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length,pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if(list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if(info != null) {
                VideoVo vo = VideoVo.init(info, video);
                vos.add(vo);
            }
        }

        return new PageResult(page,pagesize,0l,vos);
    }

    //评论列表
    public PageResult comments(String videoId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> comments = commentApi.findComments(videoId,CommentType.COMMENT,page,pagesize);
        //2、判断list集合是否存在
        if(CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            //修复视频评论点赞不显示bug
            String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId();
            String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
            if(redisTemplate.opsForHash().hasKey(key,hashKey)){
                comment.setLikeCount(1);
            }
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    //发布评论
    @CacheEvict(value="videos",allEntries = true)
    public void saveComments(String videoId, String comment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(videoId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.saveCommentVideo(comment1);
    }

    //视频评论点赞
    public Integer commentLike(String commentId) {
        //1、调用API查询用户是否已点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
        //2、如果已经点赞，抛出异常
        if(redisTemplate.opsForHash().hasKey(key,hashKey)) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setId(new ObjectId(commentId));
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.updateVideo(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //视频评论取消点赞
    public Integer dislikeComment(String commentId) {
        //1、调用API查询用户是否已点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
        //2、如果未点赞，抛出异常
        if(!redisTemplate.opsForHash().hasKey(key,hashKey)) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setId(new ObjectId(commentId));
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delCommentVideo(comment);
        //4、拼接redis的key，删除点赞状态
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    //点赞
    public Integer likeVideo(String videoId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(videoId,UserHolder.getUserId(), CommentType.LIKE);
        //2、如果已经点赞，抛出异常
        if(hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.saveVideo(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //取消点赞
    public Integer dislikeVideo(String videoId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(videoId,UserHolder.getUserId(),CommentType.LIKE);
        //2、如果未点赞，抛出异常
        if(!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.deleteVideo(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    //关注用户
    public void userFocus(String videoId) {
        //1.判断用户是否已经关注
        //判断数据是否存在
        Boolean exists = focusApi.isFocus(videoId, UserHolder.getUserId());
        if (exists){
            throw new BusinessException(ErrorResult.error());
        }
        //3.尚且没有关注过该用户，FocusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setVideoUserId(Long.valueOf(videoId));
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setCreated(System.currentTimeMillis());
        //3.1 将focusUser数据保存到数据库中
        focusApi.save(focusUser);
        //4.将关注数据同步到redis中
        String key = Constants.FOCUS_USER_KEY + videoId;
        String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    public void userUnFocus(String videoId) {
        //判断数据是否存在
        Boolean exists = focusApi.isFocus(videoId, UserHolder.getUserId());
        if (!exists){
            throw new BusinessException(ErrorResult.error());
        }
        //3.尚且没有关注过该用户，FocusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setVideoUserId(Long.valueOf(videoId));
        focusUser.setUserId(UserHolder.getUserId());
        //3.1 将FollowUser数据从数据库中删除
        focusApi.delete(focusUser);
        //4.将关注数据同步到redis中
        String key = Constants.FOCUS_USER_KEY + videoId;
        String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
    }
}
